package com.lagou.springBootRocketmq.controller;

import com.lagou.springBootRocketmq.entity.Order;
import com.lagou.springBootRocketmq.entity.OrderStatus;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

import static com.lagou.springBootRocketmq.cons.Constant.GOODS_COUNT;
import static com.lagou.springBootRocketmq.cons.Constant.ORDER_TIPIC;

@RestController
@RequestMapping("/api/mq")
public class RocketMQController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping("/rockt/send")
    public String send(String msg) {
        Order order = new Order();
        // 生成订单ID
        order.setOrderId(UUID.randomUUID().toString());
        order.setUserId("zhangsan");
        order.setContent(msg);
        order.setOrderStatus(OrderStatus.NEW);

        Integer goodsCount = Integer.valueOf(redisTemplate.opsForValue().get(GOODS_COUNT));
        if (goodsCount <= 0) return "库存不足";

        // MQ发送消息
        System.out.println("--->发送MQ消息");
        rocketMQTemplate.asyncSend(ORDER_TIPIC, order, new SendCallback() {
            // 发送消息后函数拦截
            @Override
            public void onSuccess(SendResult sendResult) {
                // 修改库存
                int cnt = goodsCount - 1;
                redisTemplate.opsForValue().set(GOODS_COUNT, String.valueOf(cnt));
                System.out.println("修改库存-》" + cnt);
            }

            @Override
            public void onException(Throwable throwable) {
            }
        });
        System.out.println("--->发送MQ消息-end");
        // MQ发送消息-end

        return "ok";
    }

}
